<?php
/**
 * Created by Mr.hu.
 * Date: 2017/3/13
 * Time: 14:10
 * Description:'分销商品管理'
 */
namespace   backend\controllers;
use bc\controller\BackendController;
use bc\model\distribution\DistributionModel;
use bc\model\distribution\TempleModel;
use bc\model\ProductModel;
use bc\util\backend\Page;
use bc\util\Uploader;
use yii;
class DistributionController extends BackendController{
    /**
     * Created by Mr.hu.
     * Description:分销商品添加页面
     */
    public function actionIndex()
    {
        $compact=array();
        //产品列表
        $productModel=new   ProductModel();
        $product_list=$productModel->getProductInfo();
        $compact['product_list']=$product_list;

        //如果是详情页面
        $distributionModel=new DistributionModel();
        $id=$this->get('id');
        if($id){
            $compact['info']=$distributionModel->getOneInfo($id);
        }
        return $this->render('index',$compact);
    }


    /**
     * Created by Mr.hu.
     * Description:1 添加或者 2编辑
     */
    public function actionDeal()
    {
        //上传图片
        $return_info=$this->uploadPic($_FILES['image_data']);
        if($return_info['status']){
            $return_info=$return_info['info'];
        }else{
            $this->redirect('index');
        }




        //1添加，2修改
        $distributionModel=new DistributionModel();
        $data=$this->post();
        $type=empty($data['distribution_id'])?1:2;
        if($type==1){
            $data['create_time']=date('Y-m-d H:i:s');
            $data['is_del']=0;
            $distributionModel->setScenario('add');
        }elseif($type==2){
            $data['update_time']=date('Y-m-d H:i:s');
            $distributionModel->setScenario('edit');
        }
        $distributionModel->attributes=$data;
        if($distributionModel->validate()){
        switch ($type){
            case 1:
                $distributionModel->insert();
                $insert_id=Yii::$app->db->getLastInsertID();
                $update_result=$this->save_for_databases($insert_id,$return_info,1);
                break;
            case 2:
                $distributionModel->modify(array_filter($distributionModel->getAttributes()),$data['distribution_id']);
                $update_result=$this->save_for_databases($data['distribution_id'],$return_info,2);
                break;
        }

        if($update_result){
            $this->redirect('/distribution/list');
        }
        }
        $this->redirect('/distribution/index');

    }

    /**
     * Created by Mr.hu.
     * @param $distribution_id
     * @param $template_path_arr
     * $type 1添加  2更新
     * Description:更新代言人模板表
     */
    private function save_for_databases($distribution_id,$template_path_arr,$type=1)
    {
        $now_time=date('Y-m-d H:i:s');
        $filed=array('distribution_id','template_path','is_del','create_time','update_time');
        $value_arr=array();
        if($type==2){
            TempleModel::deleteAll(['distribution_id'=>$distribution_id]);
        }

        foreach ($template_path_arr as $v){
            array_push($value_arr,array($distribution_id,$v['url'],0,$now_time,$now_time));
        }
        return Yii::$app->db->createCommand()->batchInsert('bc_product_distribution_template',$filed,$value_arr)->execute();
    }


    /**
     * Created by Mr.hu.
     * Description:上传照片
     */
    public function uploadPic($file_info)
    {
        //多个文件上传，模拟一个文件多次上传
        $files_name=$file_info['name'];
        $_FILES=array();
        foreach ($files_name as $k=>$v){
            $_FILES['upload_file'.$k]['name']=$v;
            $_FILES['upload_file'.$k]['type']=$file_info['type'][$k];
            $_FILES['upload_file'.$k]['tmp_name']=$file_info['tmp_name'][$k];
            $_FILES['upload_file'.$k]['error']=$file_info['error'][$k];
            $_FILES['upload_file'.$k]['size']=$file_info['size'][$k];
        }
        //文件配置项
        $file_config=array(
            'savePath'=>UPLOAD_PATH,
            'allowFiles'=>array('.jpg','.png','.jpeg'),
            'maxSize'=>2*1024,
        );
        $after_info=array();
        foreach ($_FILES as $key=>$value){
            $tool=new Uploader($key,$file_config);
            $return_file_info=$tool->getFileInfo();
            if($return_file_info['state']==='SUCCESS'){
                array_push($after_info,$return_file_info);
            }else{
                return array('status'=>0,'info'=>$return_file_info['state']);
            }
        }

        return array('status'=>1,'info'=>$after_info);
    }

    /**
     * Created by Mr.hu.
     * Description:列表展示页面
     */
    public function actionList()
    {
        $module=new DistributionModel();
        $list=$module->getList(null,$this->get('page',1),self::PAGE_SIZE);
        array_walk($list,function (&$item){
           $item['product_name']=$this->getProductName($item['product_id']);
        });
        $total = $module->getTotal();
        $pagination = new Page($total, self::PAGE_SIZE);
        return $this->render('list',['list'=>$list,'page'=>$pagination]);
    }

    /**
     * Created by Mr.hu.
     * @param $product_id
     * Description:获取商品名称
     */
    private function getProductName($product_id)
    {
        $info=ProductModel::findOne(['product_id'=>$product_id]);
        return $info['product_name'];
    }




}